import "./style.less";
import BottomNavigation from "@mui/material/BottomNavigation";
import BottomNavigationAction from "@mui/material/BottomNavigationAction";
import home1 from "@/assets/images/tabbar/home_1.png";
import home2 from "@/assets/images/tabbar/home_2.png";
import fast from "@/assets/images/tabbar/fast.png";
import my_1 from "@/assets/images/tabbar/my_1.png";
import my_2 from "@/assets/images/tabbar/my_2.png";
import { SyntheticEvent, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";

const navs = [
  {
    path: "/home",
    txt: "首页",
    icon: home1,
    active: home2,
  },
  {
    path: "/fast",
    txt: "快速答题",
    icon: fast,
    active: fast,
  },
  {
    path: "/mine",
    txt: "我的",
    icon: my_1,
    active: my_2,
  },
];

export default function TabBar() {
  const navigator = useNavigate();
  const location = useLocation();
  // 点击切换tabar栏
  const switchFn = (event: SyntheticEvent, newValue: number) => {
    setValue(newValue);
    navigator(navs[newValue].path);
  };
  // 初始化tabar显示问题
  const index = navs.findIndex((item) => item.path === location.pathname);
  const [value, setValue] = useState(index);

  return (
    // 判断tabar是否显示
    <div className="tabBar" style={{ display: index >= 0 ? "block" : "none" }}>
      <BottomNavigation
        showLabels
        value={value}
        onChange={(event, newValue) => switchFn(event, newValue)}
      >
        {navs.map((item, index) => (
          <BottomNavigationAction
            key={index}
            label={item.txt}
            icon={<img src={value === index ? item.icon : item.active} />}
          />
        ))}
      </BottomNavigation>
    </div>
  );
}
